package com.memory.admin.earn.controller;

import com.memory.modules.business.domain.earn.CurDayPrice;
import com.memory.modules.business.domain.earn.DayEarn;
import com.memory.modules.business.service.earn.CurDayPriceService;
import com.memory.modules.business.service.earn.impl.DayEarnServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.WebRequest;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

@Controller
@RequestMapping("/business/earn")
@RequiredArgsConstructor
public class EarnController {

    @InitBinder
    public void initBinder(WebDataBinder binder, WebRequest request) {
        DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

    private final CurDayPriceService curDayPriceService;

    private final DayEarnServiceImpl dayEarnServiceImpl;

    @GetMapping("list")
    public String list(Model model) {
        ExampleMatcher exampleMatcher = ExampleMatcher.matching();
        DayEarn dayEarn = new DayEarn();
        Example<DayEarn> example = Example.of(dayEarn, exampleMatcher);
        final Page<DayEarn> page = dayEarnServiceImpl.findPage(example);
        page.getContent().stream().forEach(dayEarn1 ->{
            CurDayPrice curDayPrice = curDayPriceService.findByDate(dayEarn1.getCreateDate());
            if (curDayPrice !=null) {
                dayEarn1.setStaticUsdtEarn(curDayPrice.getUsdtPrice().multiply(dayEarn1.getTotalEarn()));
            }
        });
        model.addAttribute("list", page.getContent());
        model.addAttribute("page", page);
        return "/business/earn/list";
    }
}
